using System;
using Microsoft.Xna.Framework;
using System.Linq;
using Map;

namespace Map_Creator.MapInfo
{
    public class Layer : LayerStruct
    {
        public ExtendedTreeNode Node;

        public int opacity = 100;

        public Map AssociatedMap
        {
            get { return (Map)Map; }
            set { Map = value; }
        }

        public Layer(int level, Map map, short defaultValue, int ID = 0) : base(ID)
        {
            Level = level;
            AssociatedMap = map;
            data = new TileStructGrid(AssociatedMap.GridSize.X, AssociatedMap.GridSize.Y);

            if (defaultValue == -1) return;
            var defaultTile = new Tile{TileSetIndex = 0, Value = defaultValue};

            for (var i = 0; i < AssociatedMap.GridSize.X; i++)
            {
                for (var j = 0; j < AssociatedMap.GridSize.Y; j++)
                {
                    data[i, j] = defaultTile;
                }
            }
        }

        public Layer(int ID = 0) : base(ID)
        {
            
        }

        public TileStruct this[int X, int Y]
        {
            get { return data[X, Y]; }
            set { data[X, Y] = value; }
        }

        public TileStruct this[Point pos]
        {
            get { return data[pos.X, pos.Y]; }
            set { data[pos.X, pos.Y] = value; }
        }

        public override void Delete()
        {
            if (AssociatedMap == null) return;

            AssociatedMap.Layers.Remove(this);

            foreach (var curLayer in AssociatedMap.Layers.Where(curLayer => curLayer.Level > Level))
            {
                curLayer.Level--;
            }
            AssociatedMap.Levels--;

            if (AssociatedMap.CurrentLayer == this)
            {
                AssociatedMap.CurrentLayer = 
                    AssociatedMap.Levels > 0 ?
                        AssociatedMap[Math.Min(Level, AssociatedMap.Levels - 1)] : 
                        null;
            }

            var parent = Node.Parent;
            Node.Remove();
            if (parent.Nodes.Count == 0)
                parent.Remove();

            // set null associated map so remove wont ever happen twice :O
            AssociatedMap = null;

            base.Delete();
        }
    }
}